﻿using System;
using LtccApi.Models;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using MySql.Data.MySqlClient;

namespace LtccApi.Controllers
{
  /// <summary>
  /// Store controller.
  /// </summary>
  [Route("api/[Controller]")]
  [ApiController]
  public class StoreController : Controller
  {
    LtccContext mLtccContext;
    /// <summary>
    /// Initializes a new instance of the <see cref="T:LtccApi.Controllers.StoreController"/> class.
    /// </summary>
    /// <param name="ltccContext">Ltcc context.</param>
    public StoreController(LtccContext ltccContext)
    {
      mLtccContext = ltccContext;
    }
    /// <summary>
    /// 店铺列表
    /// </summary>
    /// <returns>The list.</returns>
    [HttpPost]
    public IActionResult List(StoreQuery storeQuery)
    {
      var qurerResult = mLtccContext.StoreTires.AsQueryable();
      //过滤类型
      if (storeQuery.Type == VEHICLE_TYPE.CAR_TYPE)
      {
        qurerResult = qurerResult.Where(m => m.CarFlag == 1);
      }
      else
      {
        qurerResult = qurerResult.Where(m => m.TruckFlag == 1);
      }
      //过滤搜索文本
      if (storeQuery.SearchText != "")
      {
        qurerResult = qurerResult.Where(m => m.Name.Contains(storeQuery.SearchText));
      }
      var data = mLtccContext.StoreTires.FromSql(
          "select *, acos(cos({0}*pi()/180 )*cos(lat*pi()/180)*cos({1}*pi()/180 -lng*pi()/180)+sin({2}*pi()/180 )*sin(lat*pi()/180))*6370996.81/1000 as distance from bj_stores where (lat - {3}) * (lat - {4}) + (lng - {5}) * (lng - {6}) <= (0.01 * 150) * (0.01 * 150) ORDER BY distance LIMIT {7},{8} ",
          storeQuery.Latitude,
          storeQuery.Longitude,
          storeQuery.Latitude,
          storeQuery.Latitude,
          storeQuery.Latitude,
          storeQuery.Longitude,
          storeQuery.Longitude,
          storeQuery.IndexPage * storeQuery.PageSize,
          storeQuery.PageSize
      );
      //分页
      //List<StoreTire> listData = qurerResult.Skip(storeQuery.IndexPage * storeQuery.PageSize).Take(storeQuery.PageSize).ToList();

      return Ok(data);
    }
  }
}
